//
//  WebServiceCommonRequest.m
//  ERP
//
//  Created by QA on 15/8/24.
//  Copyright (c) 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "WebServiceCommonRequest.h"
#import "AESCrypt.h"
#import "NSKeyedArchiverUserLogin.h"
#import "ConfigurationHelper.h"
#import "HttpNativeConnect.h"

@interface WebServiceCommonRequest()

@property (nonatomic, strong) NSMutableDictionary *jsonDictionary;
@property (nonatomic, strong) NSMutableDictionary *parametersDictionary;

@end

@implementation WebServiceCommonRequest

- (id)init
{
    self = [super init];
    if (self) {
        [self initSetupIpAddress];
    }
    return self;
}

- (void)initSetupIpAddress
{
    self.jsonDictionary = [NSMutableDictionary dictionary];
    self.parametersDictionary = [NSMutableDictionary dictionary];
}

#pragma mark 基础数据设置

//添加传递参数
- (void)addParameterKey:(id)key value:(id)value defaults:(id)defaults
{
    if (!value) value = defaults;
    
    if([value isKindOfClass:[NSString class]]){
        NSString *valueString = value;
        if(valueString.length <= 0) value = defaults;
    }
    
    if (!value) value = @"";
    [self.parametersDictionary setObject:value forKey:key];
}

//移除所有传递参数
- (void)removeAllParameter
{
    if(self.parametersDictionary)
    [self.parametersDictionary removeAllObjects];
}

//添加传递参数
- (void)addParameterKey:(id)key value:(id)value
{
    if (!value) value = @"";
    [self.parametersDictionary setObject:value forKey:key];
}

//接口类型 IntType
- (void)setInterfaceType:(InterfaceType)interfaceType
{
    NSNumber *value = [NSNumber numberWithInteger:interfaceType];
    [self.jsonDictionary setValue:value forKey:@"IntType"];
}

//站点类型 SiteId
- (void)setStationID:(NSInteger)stationID
{
    NSNumber *value = [NSNumber numberWithInteger:stationID];
    [self.jsonDictionary setValue:value forKey:@"SiteId"];
}

//用户ID UserId
- (void)setUserID:(NSInteger)userID
{
    NSNumber *value = [NSNumber numberWithInteger:userID];
    [self.jsonDictionary setValue:value forKey:@"UserId"];
}

//模块类 FunType
- (void)setModuleType:(NSString *)moduleType
{
    [self.jsonDictionary setValue:moduleType forKey:@"FunType"];
}

//返回结果类型 IsOrder
- (void)setResultBackType:(ResultBackType)resultBackType
{
    NSNumber *value = [NSNumber numberWithInteger:resultBackType];
    [self.jsonDictionary setValue:value forKey:@"IsOrder"];
}

//企业简码 BriefCode
- (void)setBriefCode:(NSString *)briefCode
{
    [self.jsonDictionary setValue:briefCode forKey:@"EnterpriseCode"];
}

#pragma mark 创建连接

- (void)createSetupServiceArgs
{
    ServiceArgs *serviceArgs = [[ServiceArgs alloc] init];
    
    ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
    NSString *ipAddress = [NSString stringWithFormat:@"%@%@",model.IpAddress,ERPWebServiceUrl];
    
    [serviceArgs setWebURL:[NSURL URLWithString:ipAddress]];
    [serviceArgs setServiceNameSpace:ERPWebServiceNameSpace];
    [serviceArgs setServiceGUID:ERPWebServiceGUID];
    
    [self buildParameterToJson:serviceArgs];
    [self setServiceArgs:serviceArgs];
}

- (void)buildParameterToJson:(ServiceArgs*)serviceArgs
{
    //组织机构和用户ID
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [self setUserID:[userInfo.Id integerValue]];
    
    if (![self.jsonDictionary objectForKey:@"SiteId"])
        [self setStationID:0];
    
    if(![self.jsonDictionary objectForKey:@"EnterpriseCode"]){
        ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
        if(model)[self setBriefCode:model.briefCode];
        else [self setBriefCode:@""];
    }
    
    //参数添加
    if (self.parametersDictionary)
        [self.jsonDictionary setValue:self.parametersDictionary forKey:@"Parameter"];
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil) {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSString *jsonEncrypt = [AESCrypt encrypt:jsonString];
        
        NSDictionary *dictionary = [NSDictionary dictionaryWithObject:jsonEncrypt forKey:@"jsonParm"];
        NSArray *valueArray = [NSArray arrayWithObjects:dictionary, nil];
        [serviceArgs serviceMethodName:@"Common_PublicService" soapMessageArray:valueArray];
    }
}

#pragma mark 同步请求数据

- (ServiceResultModel*)startSyncConnect
{
    [self createSetupServiceArgs];
    return [super startSyncConnect];
}

#pragma mark 异步请求数据

-(void)startAsyncConnectCompleted:(finishBlockRequest)finish failed:(failedBlockRequest)failed abnormal:(abnormalBlockRequest)abnormal
{
    //连接类型 0-Webserver 1-javaweb
    ConfigurationCodeing *configuration = [ConfigurationHelper getConfigurationData];
    if([configuration.serverType integerValue] == 0){
        //按照WebServer方式执行
        [self createSetupServiceArgs];
        [super startAsyncConnectCompleted:finish failed:failed abnormal:abnormal];
    } else if([configuration.serverType integerValue] == 1) {
        //按照JavaWeb方式执行
        [self javaHttpPlatformRequestCompleted:finish failed:failed abnormal:abnormal];
    }
}

#pragma mark JAVA平台异步请求数据

-(void)javaHttpPlatformRequestCompleted:(finishBlockRequest)finish failed:(failedBlockRequest)failed abnormal:(abnormalBlockRequest)abnormal
{
    //组织机构和用户ID
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [self setUserID:[userInfo.Id integerValue]];
    
    if (![self.jsonDictionary objectForKey:@"SiteId"])
        [self setStationID:0];
    
    if(![self.jsonDictionary objectForKey:@"EnterpriseCode"]){
        ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
        if(model)[self setBriefCode:model.briefCode];
        else [self setBriefCode:@""];
    }
    
    //参数添加
    if (self.parametersDictionary)
        [self.jsonDictionary setValue:self.parametersDictionary forKey:@"Parameter"];
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
    if(error) {
        failed(error, nil); return;
    }
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonEncrypt = [AESCrypt encrypt:jsonString];
    
    //请求接口数据
    [[HttpNativeConnect shareInstance] requestWithParamsString:jsonEncrypt success:^(HttpOutputResult *responseObject) {
        ServiceResultModel *model = [[ServiceResultModel alloc] init];
        model.statusCode = 200;
        model.resultArray = responseObject.objectArray;
        finish(model, nil);
    } failure:^(NSError * _Nonnull error) {
        failed(error, error.userInfo);
    }];
}

#pragma mark - 对象清理

- (void)dealloc
{
    if (self.parametersDictionary)
        [self.parametersDictionary removeAllObjects];
    
    self.parametersDictionary = nil;
}

@end
